// Copyright 2013 Petar Maymounkov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package focus

import (
	"circuit/kit/rh"
	"circuit/kit/rh/ns"
	"circuit/kit/rh/xy"
)

// loci is a namespace of type ns.MapDir listing all circuit loci.
type loci struct {
	peer    *Peer
	peers   PeerFunc
	shutter rh.FID // Non-cross
}

func newLoci(peer *Peer, peers PeerFunc, shutter rh.FID) *loci {
	return &loci{
		peer:    peer,
		peers:   peers,
		shutter: shutter,
	}
}

func (l *loci) Map() map[string]ns.Dir { // If Map panics, the panic will be reported as ErrIO to RH, and subsequently syscall.EIO to FUSE.
	bulk := l.peers()
	dir := make(map[string]ns.Dir)
	for _, peer := range bulk {
		//
		if peer.ID() == l.peer.ID() {
			dir[peer.Key()] = l.shutter
			continue
		}
		ysrv := xy.YServer{peer.Shutter}
		yssn, err := ysrv.SignIn("focus/"+l.peer.Key(), "/")
		if err != nil {
			continue
		}
		yfid, err := yssn.Walk(nil)
		if err != nil {
			continue
		}
		dir[peer.Key()] = yfid
	}
	return dir
}
